<?php

namespace App\Http\Controllers\Admin;

use App\Models\Agency;
use App\Models\Device;
use App\Models\File;
use App\Models\Type;
use App\Models\User;
use App\Models\UserHistory;
use App\Models\Verify;
use App\Support\Enum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

/**
 * Class UserController
 * @package App\Http\Controllers\Admin
 */
class UserController extends BaseController
{
    /**
     * 账号列表
     */
    public function index(Request $request)
    {
        $admin = $this->getAdmin();
        $isSchool = $this->isSchool();
        $query = $request->only(['name', 'phone', 'agency_id']);

        if($isSchool){
            $query['agency_id'] = $admin->agency->id;
        }
        $where = User::selectQuery($query);
        $users = User::where($where)->orderBy("id", "desc")->paginate(config('site.other.paginate'));
        $users = $users->appends($query);
        $agencies = Agency::all();

        return backendView('user.index', compact('users','query', 'isSchool', 'agencies'));
    }

    /**
     * 平台添加用户账号
     * 数据信息与接口添加有差异
     * api部分：
     * todo：统一
     *
     *
     * @param Request $request
     * @param null $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request, $id = null)
    {
        $isSchool = $this->isSchool();
        if ($request->isMethod('POST')) {
            $where = [
                'phone' => $request->input('phone'),
                'agency_id' => $request->input('agency_id'),
            ];
            //'name', 'password','phone', 'type_id', 'status'
            $this->validate($request, [
                'name' => 'required',
                'password' => 'required|confirmed', // password_confirmation
                //'phone' => 'required|min:11|max:11|unique:users',
                'phone' => ['required',
                    'min:11', 'max:11',
                    Rule::unique('users')
                        ->where(function($query) use($where){
                            return $query->where($where);
                        })
                    ],
                'agency_id' => 'required|exists:agencies,id',
                'status' => 'required|in:0,1'
            ], [], [
                'name' => __('Username'),
                'password' => __('Password'),
                'phone' => __('Mobile'),
                'agency_id' => '机构',
                'status' => __('Status')
            ]);

            $data = $request->only(['name', 'password', 'phone', 'status', 'agency_id']);

            // $data['password'] = bcrypt($data['password']);
            $data['type_id'] = 1;

            if (User::add($data)) {
                return redirect()->route('admin.user.index')->with('success', __('Edit success'));
            }

            return back()->with('error', __('Create failed'))->withInput();

        } else {
            $agencies = Agency::all();
            $thisAgencyId = $this->getAdmin()->agency ? $this->getAdmin()->agency->id : null;

            $types = Type::where("status", 1)->get();
            return backendView('user.add', compact("types", "agencies", "thisAgencyId", "isSchool"));
        }
    }

    /**
     * 编辑账号
     * @param Request $request
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function edit(Request $request, $id = null)
    {
        /**
         * @var $user User
         */
        $user = User::find($id);
        if (empty($user)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod('POST')) {

            $where = [
                'phone' => $request->input('phone'),
                'agency_id' => $request->input('agency_id'),
            ];
            $this->validate($request, [
                'name' => 'required',
                'password' => 'nullable|confirmed',
                'phone' => [
                    'required',
                    'max:11',
                    "min:11",
                    //Rule::unique('users')->ignore($user->id),
                    Rule::unique('users')
                        ->where(function($query) use($where){
                            return $query->where($where);
                        })->ignore($user->id)
                ],
               // 'type_id' => 'required|exists:types,id',
                'status' => 'required|in:0,1'
            ], [], [
                'name' => __('Username'),
                'password' => __('Password'),
                'password_confirmation' => __('Confirm Password'),
                'phone' => __('Mobile'),
               // 'type_id' => __('Type'),
                'status' => __('Status')
            ]);

            $data = $request->only(['name', 'password', 'phone', 'type_id', 'status']);
            $data['password'] = bcrypt($data['password']);

            if ($user->update($data)) {
                return redirect()->route('admin.user.index')->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'))->withInput();

        } else {
            $types = Type::where("status", 1)->get();
            return backendView('user.edit', compact('user', 'types'));
        }
    }


    /**
     * 查看账号
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function view($id = null)
    {
        /**
         * @var $user User
         */
        $user = User::find($id);
        if (empty($user)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        return backendView('user.view', compact('user'));
    }

    /**
     * 禁用或者启用用户
     *  @param null $id
     * */
    public function enable($id){

        /**
         * @var $user User
         */
        $user = User::find($id);

        if (empty($user)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        if ($user->update(['status'=>abs($user->status - 1)])){
            return back()->with('success', __('Edit success'))->withInput();
        }

        return back()->with('error', '失败');
    }

    /**
     *
     * @Date 2020/9/30 上午10:27
     * @param $agency_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxAgencyUser(Request $request){
        $agency_id = $request->input("agency_id");
        $agency = Agency::find($agency_id);
        if (empty($agency)){
            return response()->json(['status'=>300]);
        }

        $users = User::where("agency_id", $agency_id)->get();

        return response()->json(['status'=>200, 'users'=>$users]);
    }
}
